﻿using SuperSocket.ProtoBase;
using System;
using System.Buffers;
using System.Text;

namespace SuperSocket.Client.HttpCode;

internal sealed class HttpChunkPipeLineFilter : TerminatorPipelineFilter<HttpRequest>
{
    private static readonly ReadOnlyMemory<byte> Terminator = "\r\n"u8.ToArray().AsMemory();

    private readonly HttpRequest _request;

    public HttpChunkPipeLineFilter(HttpRequest request)
        : base(Terminator)
    {
        _request = request;
    }

    protected override HttpRequest DecodePackage(ref ReadOnlySequence<byte> buffer)
    {
        var chunksizeString = buffer.GetString(Encoding.UTF8);

        if (string.IsNullOrEmpty(chunksizeString))
            throw new ArgumentNullException("chunksizeString");

        var chunkSize = Convert.ToInt32(chunksizeString, 16); //16转换到10进制

        if (chunkSize == 0)
            throw new ArgumentNullException("chunkSize");

        NextFilter = new HttpBodyPipelineFilter(chunkSize, _request);

        return default;
    }
}